package com.hsxc.cdz.trans.bill;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.hsxc.cdz.base.bean.MyUser;
import com.hsxc.cdz.base.bean.Reserv;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hsxc.cdz.base.util.CommonUtils;
import com.hsxc.cdz.base.util.TimeFormatter;
import com.hsxc.cdz.mgmt.GlobalManager;
import com.hsxc.cdz.monitor.FSM.CachePile;
import com.hsxc.cdz.trans.bill.CacheTrade.TradeStatus;

/**
 * @author 作者: 陈钊
 * @version 创建时间：2016年6月24日 上午10:45:15 类说明 ：
 */
public class TradeManager {

	public static Map<String, CacheTrade> tradeMap = new ConcurrentHashMap<>();
	public static final int SUCCESS = 0;
	public static final int FAILURE = 1;
	public static final int ERR_DATA = 2;
	public static final int NO_TRADE = 3;
	public static final int NO_CACHEPILE = 4;
	public static final int NO_INSERT = 5;
	public static final int FAULT = 6;
	public static final int LOCKED = 7;

	Logger logger = LoggerFactory.getLogger(TradeManager.class);

	public int newTrade(CacheTrade trade) {

		/*
		 * if (trade == null) { System.out.println("加入交易失败"); return 1; }
		 * System.out.println("创建交易的方法中交易信息为---" + trade.toString()); // if
		 * (tradeMap.put(trade.getTid(), trade) == null) {
		 * System.out.println("创建交易时---" + tradeMap.get(trade.getTid())); return
		 * 0; }
		 * 
		 * return 1;
		 */
		if (trade == null) {
			logger.info("Trans: new Trade,trade is " + trade);
			return FAILURE;
		}
		tradeMap.put(trade.getTid(), trade);
		return SUCCESS;

	}

	public int delTrade(String tid) {
		// remove 肯定会成功
		tradeMap.remove(tid);
		/*
		 * if (tradeMap.remove(tid) == null) return 1;
		 */
		return 0;
	}

	public boolean containTrade(String tid) {
		return tradeMap.containsKey(tid);
	}

	public CacheTrade getTradeByOpenId(String openId) {
		Iterator<Map.Entry<String, CacheTrade>> entries = tradeMap.entrySet().iterator();
		while (entries.hasNext()) {

			Map.Entry<String, CacheTrade> entry = entries.next();

			CacheTrade cacheTrade = entry.getValue();
			if (cacheTrade != null) {
				if (cacheTrade.getOpenId().equals(openId)) {
					return cacheTrade;
				} else {
					return null;
				}
			}
		}
		return null;
	}

	public CacheTrade getTradeByUserNo(String userNo) {
		Iterator<Map.Entry<String, CacheTrade>> entries = tradeMap.entrySet().iterator();
		while (entries.hasNext()) {

			Map.Entry<String, CacheTrade> entry = entries.next();

			CacheTrade cacheTrade = entry.getValue();
			if (cacheTrade != null) {
				if (cacheTrade.getUserNo().equals(userNo)) {
					return cacheTrade;
				} else {
					return null;
				}
			}
		}
		return null;
	}

	/**
	 * 根据openId删除交易
	 * 
	 * @param openId
	 * @return
	 */
	public int delTradeByOpenId(String openId) {
		CacheTrade cacheTrade = getTradeByOpenId(openId);
		if (cacheTrade == null) {
			logger.error("不存在交易");
			return 1;
		}
		tradeMap.remove(cacheTrade.getTid());
		return 0;
	}

	public CacheTrade getTrade(String tid) {
		return tradeMap.get(tid);
	}

	public CacheTrade getPayTrade(String pileNO) {
		return null;
	}

	public CacheTrade getTrade(String pileNO, String userNO) {
		Iterator<Map.Entry<String, CacheTrade>> entries = tradeMap.entrySet().iterator();
		while (entries.hasNext()) {

			Map.Entry<String, CacheTrade> entry = entries.next();

			CacheTrade cacheTrade = entry.getValue();
			if (cacheTrade != null) {
				if (cacheTrade.getUserNo().equals(userNO) && cacheTrade.getPileNo().equals(pileNO)) {
					return cacheTrade;
				} else {
					return null;
				}
			}
		}
		return null;
	}

	/**
	 * 获取正在进行中的交易
	 * @param pileAddress
	 * @return
	 */
	public CacheTrade getTradeByPileAddress(String pileAddress) {
		Iterator<Map.Entry<String, CacheTrade>> entries = tradeMap.entrySet().iterator();
		while (entries.hasNext()) {

			Map.Entry<String, CacheTrade> entry = entries.next();

			CacheTrade cacheTrade = entry.getValue();
			if (cacheTrade != null) {
				if (cacheTrade.getCachePile().getAddress().equals(pileAddress)
						&& cacheTrade.getTradeStatus() == TradeStatus.TRADE_STATUS_ON) {
					return cacheTrade;
				}
			}
		}
		return null;
	}
	public CacheTrade getTradePREPAREByPileAddress(String pileAddress) {
		Iterator<Map.Entry<String, CacheTrade>> entries = tradeMap.entrySet().iterator();
		while (entries.hasNext()) {

			Map.Entry<String, CacheTrade> entry = entries.next();

			CacheTrade cacheTrade = entry.getValue();
			if (cacheTrade != null) {
				if (cacheTrade.getCachePile().getAddress().equals(pileAddress)
						&& cacheTrade.getTradeStatus() == TradeStatus.TRADE_STATUS_READY) {
					return cacheTrade;
				}
			}
		}
		return null;
	}
	public CacheTrade getTradeFAILByPileAddress(String pileAddress) {
		Iterator<Map.Entry<String, CacheTrade>> entries = tradeMap.entrySet().iterator();
		while (entries.hasNext()) {

			Map.Entry<String, CacheTrade> entry = entries.next();

			CacheTrade cacheTrade = entry.getValue();
			if (cacheTrade != null) {
				if (cacheTrade.getCachePile().getAddress().equals(pileAddress)
						&& cacheTrade.getTradeStatus() == TradeStatus.TRADE_STATUS_READY) {
					return cacheTrade;
				}
			}
		}
		return null;
	}

	public boolean modifyTrade(String tid, CacheTrade cacheTrade) {
		CacheTrade cacheTrade1 = getTrade(tid);
		cacheTrade1.setUserNo(cacheTrade.getUserNo());
		cacheTrade1.setStartTime(cacheTrade.getStartTime());
		cacheTrade1.setStopTime(cacheTrade.getStopTime());
		cacheTrade1.setTradeStatus(cacheTrade.getTradeStatus());
		tradeMap.put(tid, cacheTrade1);
		return true;
	}

	/**
	 * 生成交易
	 * 
	 * @param pileNO
	 * @param openId
	 * @param type
	 *            1--微信公众号用户 2--app用户
	 * @return
	 */
	public int createTrade(String pileNO, String openId, int type) {
		int result;
		// if (pileNO == null || userNo == null) {
		//
		// return "5";//参数为空
		// }
		CachePile cachePile = GlobalManager.pileManager.getPile(pileNO);
		if (cachePile == null) {
			result = 4;
			logger.error("内存中不存在该充电桩");
			return result;
		}
		switch (cachePile.lock()) {
		case CachePile.PILE_STATUS_INSERTED:
			String tid = CommonUtils.getTID();
			// // 设置交易的属性
			CacheTrade cacheTrade = new CacheTrade();
			cacheTrade.setCachePile(cachePile);
			cacheTrade.setTid(tid);
			cacheTrade.setUserNo(tid);
			cacheTrade.setOpenId(openId);
			cacheTrade.setTradeStatus(TradeStatus.TRADE_STATUS_READY);
			cacheTrade.setStartTime(TimeFormatter.toTimeYear());
			cacheTrade.setType(type);
			if (newTrade(cacheTrade) == 0) {
				logger.error("插入交易失败");
			}
			result = 3;
			logger.info("已经返回交易tid，交易tid=" + tid);
			break;
		case CachePile.PILE_STATUS_LOCKED:
			result = 0;// + "电桩已经被占用";
			break;
		case CachePile.PILE_STATUS_UNINSERT:

			// 这里需要解锁电桩，并删除该交易

			result = 2;// + "电桩未连枪";
			break;
		case CachePile.PILE_STATUS_FAULT:
			result = 1;// + "电桩故障";
			break;
		default:
			result = 6;// 其他错误
			break;
		}
		return result;
	}

	/**
	 * 生成交易
	 * 
	 * @param pileNO
	 * @param userNo--20位数字
	 * @param type
	 *            1--微信公众号用户 4--微信app用户
	 * @return4--内存中不存在该充电桩3--tid0--电桩被占有2--电桩未连1--故障6--其他
	 */
	public Map<String,Object> createTradeWXAPP(String pileNO, String userNo, int type,int chargePort) {
		int result;
		Map<String,Object> map= new ConcurrentHashMap<>();
		// if (pileNO == null || userNo == null) {
		//
		// return "5";//参数为空
		// }
		CachePile cachePile = GlobalManager.pileManager.getPile(pileNO);
		if (cachePile == null) {
			map.put("errcode",4);
			result = 4;
			logger.error("内存中不存在该充电桩");
			return map;
		}
		int isReserv = CacheTrade.NOT_RESERVED; // 表示非预约
		String reservNo = null;
		// 根据用户名删除缓存预约，数据库预约记录不变
		Reserv reserv = GlobalManager.cacheReservManager.queryReserv(userNo, pileNO);
		if (reserv != null) {
			isReserv = CacheTrade.IS_RESERVED;
			reservNo = reserv.getResNo();
			// 正常时间内进行充电，取消定时发送短信
			//reserv.getTimer().cancel();
			GlobalManager.cacheReservManager.removeReserv(reserv.getResNo());
			GlobalManager.reservManager.updateReserv(reserv.getResNo(),false,Reserv.RESERV_STATE_FINISH);
			//将电桩改为空闲状态
			cachePile.changeStateIdle();
			//cachePile = cachePile.createCachePileCharging();
			//cachePile.setPileType(cachePile);
			GlobalManager.pileManager.newPile(cachePile);
			//设置积分
			MyUser myUser = new MyUser();
			myUser.setTel(userNo.substring(0,11));
			GlobalManager.myUserManager.updateUserByTel(myUser);

		}
		switch (cachePile.lock()) {
		case CachePile.PILE_STATUS_INSERTED:
			String tid = CommonUtils.getTID();
			// // 设置交易的属性
			CacheTrade cacheTrade = new CacheTrade();
			cacheTrade.setCachePile(cachePile);
			cacheTrade.setTid(tid);
			cacheTrade.setPileNo(pileNO);
			cacheTrade.setUserNo(userNo);
			cacheTrade.setTradeStatus(TradeStatus.TRADE_STATUS_READY);
			cacheTrade.setStartTime(TimeFormatter.toTimeYear());
			cacheTrade.setType(type);
			cacheTrade.setIsReserv(isReserv);
			cacheTrade.setReservNo(null);
			//交易指定的充电口
			cacheTrade.setChargePort(chargePort);

			// 如果是预约的需要记录预约编号
			if (isReserv == CacheTrade.IS_RESERVED)
				cacheTrade.setReservNo(reservNo);
			// 插入缓存
			GlobalManager.tradeManager.newTrade(cacheTrade);

			map.put("errcode",TradeManager.SUCCESS);
			map.put("tid",tid);
			//result = ;
			System.out.println("已经返回交易tid，交易tid=" + tid);
			System.out.println("创建交易时，用户名为=" + userNo);
			System.out.println("创建交易时电桩编号为=" + pileNO);
			break;
		case CachePile.PILE_STATUS_LOCKED:
			map.put("errcode",TradeManager.LOCKED);
			//result = TradeManager.LOCKED;// + "电桩已经被占用";
			break;
		case CachePile.PILE_STATUS_UNINSERT:
			// new Thread(new Runnable() {
			// @Override
			// public void run() {
			// cachePile.collectStatus();
			// }
			// }).start();
			// cachePile.collectStatus();
			map.put("errcode",TradeManager.NO_INSERT);
			//result = TradeManager.NO_INSERT;// + "电桩未连枪";
			break;
		case CachePile.PILE_STATUS_FAULT:
			map.put("errcode",TradeManager.FAULT);
			//result = ;// + "电桩故障";
			break;
		default:
			map.put("errcode",TradeManager.FAILURE);
			//result = ;// 其他错误
			break;
		}
		return map;
	}

	/**
	 * 
	 * @param tid
	 * @return SUCCESS--开始充电失败 FAILURE--开始成功 3-没有交易 4 没有缓冲电桩
	 */
	public int startTrade(String tid) {

		CacheTrade cacheTrade = getTrade(tid);
		if (cacheTrade == null) {
			return NO_TRADE;
		}
		CachePile cachePile = cacheTrade.getCachePile();
		if (cachePile == null) {
			return NO_CACHEPILE;
		}
		int result = cachePile.chargeStart(0, 0, 0, 0, 0.0, cacheTrade.getUserNo(), "0122");
		if (result == SUCCESS) {
			return SUCCESS;
		}
		return FAILURE;

	}

	/**
	 * 
	 * @param tid
	 * @return 0-成功 1-失败 3-没有交易4 没有缓冲电桩
	 */

	public int stopTrade(String tid) {
		CacheTrade cacheTrade = getTrade(tid);
		if (cacheTrade == null) {
			return NO_TRADE;
		}
		CachePile cachePile = cacheTrade.getCachePile();
		if (cachePile == null) {
			return NO_CACHEPILE;
		}
		// 参数
		int result = cachePile.chargeStop(0, 0, cacheTrade.getUserNo());
		if (result == SUCCESS) {
			return SUCCESS;
		}
		return FAILURE;
	}

	/**
	 * 更新交易的状态
	 * 
	 * @param tid
	 * @param tradeStatus
	 * @return0-成功 1-失败
	 */
	public int updateTrade(String tid, TradeStatus tradeStatus, double electricity, double sumFee) {
		CacheTrade cacheTrade = getTrade(tid);
		if (cacheTrade == null) {
			return FAILURE;
		}

		cacheTrade.setTradeStatus(tradeStatus);
		cacheTrade.setChargeDegree(electricity);
		cacheTrade.setChargeFee(sumFee);

		if (tradeMap.put(tid, cacheTrade) == null) {
			return FAILURE;
		}
		return SUCCESS;
	}

	public int updateTradeByHeart(String pileNo, double electricity, double sumMoney) {
		CacheTrade cacheTrade = GlobalManager.tradeManager.getTradeByPileAddress(pileNo);
		if (cacheTrade == null) {
			return FAILURE;
		}
		cacheTrade.setChargeFee(sumMoney);
		cacheTrade.setChargeDegree(electricity);

		if (tradeMap.put(cacheTrade.getTid(), cacheTrade) != null) {
			return SUCCESS;
		}
		return FAILURE;
	}
}